
package com.aizhixin.lab.login.controller;

import com.aizhixin.lab.account.dto.AccountDTO;
import com.aizhixin.lab.account.service.AccountService;
import com.aizhixin.lab.common.core.ApiReturnConstants;
import com.aizhixin.lab.common.core.DataValidity;
import com.aizhixin.lab.common.utils.TokenUtil;
import com.aizhixin.lab.company.domain.LogDomain;
import com.aizhixin.lab.company.entity.User;
import com.aizhixin.lab.company.repository.UserRepository;
import com.aizhixin.lab.company.service.LogService;
import com.aizhixin.lab.company.service.UserService;
import com.aizhixin.lab.jsrun.domian.AddAdminAccountDomain;
import com.aizhixin.lab.jsrun.domian.LoginDomain;
import com.aizhixin.lab.jsrun.domian.RegisterDomain;
import com.aizhixin.lab.jsrun.util.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/v1/user")
@Api(value = "登录API", tags = "登录登出注册")
public class LoginController {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private UserService userService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private LogService logService;
    private String TYPE_TOKEN = "token:";
    @Autowired
    private UserRepository userRepository;


    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "POST", value = "登录", response = Void.class, notes = "登录")
    public ResponseEntity<?> getCourseClassList(@ApiParam(value = "登录参数", required = false) @RequestBody LoginDomain domain, HttpServletRequest request) {
        Map<String, Object> result = new HashMap();
        User user = userRepository.findByUserNameAndDeleteFlag(domain.getUsername().trim(), 0);
        if (user == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        AccountDTO accountDTO = new AccountDTO();
        BeanUtils.copyProperties(user, accountDTO);
        String acc = JSON.toJSONString(accountDTO);
        String passwordEncode = PasswordUtil.encrypt(domain.getUsername().trim(), domain.getPassword().trim(), "ad9325e6");
        if (!user.getPassWord().equals(passwordEncode)) {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.MESSAGE, "密码错误！");
            return new ResponseEntity(result, HttpStatus.OK);
        }
        String onToken = "";
        if (user.getOntoken() == null) {
            onToken = Md5Util.md5(domain.getUsername().trim() + domain.getPassword().trim() + UUID.randomUUID().toString());

        } else {
//             redisTemplate.delete(user.getOntoken());
            onToken = Md5Util.md5(domain.getUsername().trim() + domain.getPassword().trim() + UUID.randomUUID().toString());
        }


        user.setOntoken(onToken);
        userService.save(user);

        LogDomain logDomain = new LogDomain();
        logDomain.setUserId(accountDTO.getId());
        logDomain.setOperationType("登录");
//        logService.save(logDomain);
        redisTemplate.opsForValue().set(onToken, acc, 1, TimeUnit.DAYS);
        result.put(ApiReturnConstants.SUCCESS, true);
        result.put(ApiReturnConstants.ID, onToken);
        result.put(ApiReturnConstants.DATA, accountDTO);
        return new ResponseEntity(result, HttpStatus.OK);
    }


    @RequestMapping(value = "/out", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "POST", value = "用户退出", response = Void.class, notes = "用户退出")
    public ResponseEntity<?> userOut(@RequestHeader("Authorization") String token) {
        Map<String, Object> result = new HashMap();
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(),
                    HttpStatus.UNAUTHORIZED);
        }
        User user = userRepository.findByUserNameAndDeleteFlag(account.getUserName(), 0);
        LogDomain logDomain = new LogDomain();
        logDomain.setUserId(account.getId());
        logDomain.setOperationType("登出");
        user.setOntoken(null);
        userService.save(user);
//        logService.save(logDomain);
        redisTemplate.delete(token);
        result.put(ApiReturnConstants.SUCCESS, true);
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/passReset", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "GET", value = "密码重置接口", response = Void.class, notes = "密码重置接口")
    public ResponseEntity<?> passReset(@ApiParam(value = "重置密码用户名", required = false) @RequestParam(value = "userName") String userName) {
        Map<String, Object> result = new HashMap();
        User user = userRepository.findByUserNameAndDeleteFlag(userName.trim(), 0);
        if (user != null) {
            String passwordEncode = PasswordUtil.encrypt(user.getUserName(), "dingli123", "ad9325e6");
            user.setPassWord(passwordEncode);
            user.setOntoken(null);
            userService.save(user);
        }
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/passResetAll", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "POST", value = "所有用户密码重置，第一次部署服务器时使用", response = Void.class, notes = "第一次部署服务器时使用")
    public ResponseEntity<?> passResetAll() {
        Map<String, Object> result = new HashMap();
        List<User> user = userService.findUsers();
        user.forEach(u -> {
            String passwordEncode = PasswordUtil.encrypt(u.getUserName(), "dingli123", "ad9325e6");
            u.setPassWord(passwordEncode);
            u.setOntoken(null);
            userService.save(u);
        });
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/updatePassWord", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "POST", value = "密码修改", response = Void.class, notes = "密码修改接口")
    public ResponseEntity<?> updatePassWord(@ApiParam(value = "修改密码参数", required = false) @RequestBody LoginDomain domain) {
        Map<String, Object> result = new HashMap();
        User user = userRepository.findByUserNameAndDeleteFlag(domain.getUsername().trim(), 0);
        if (user != null) {
            String passwordEncode = PasswordUtil.encrypt(user.getUserName(), domain.getPassword().trim(), "ad9325e6");
            user.setPassWord(passwordEncode);
            user.setOntoken(null);
            userService.save(user);
        }
        return new ResponseEntity(result, HttpStatus.OK);
    }


    @RequestMapping(value = "/register", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "POST", value = "注册", response = Void.class, notes = "注册")
    public ResponseEntity<?> register(@ApiParam(value = "注册参数", required = false) @RequestBody RegisterDomain domain) {
        Map<String, Object> result = new HashMap();
        User user = userService.findByJobNum(domain.getJobNum());
        if (user != null) {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.MESSAGE, "工号已存在！");
            return new ResponseEntity(result, HttpStatus.OK);
        }
        String salt = "ad9325e6";
        String userName = "";
        String passwordEncode = "";
        if (domain.getRole().equals("teacher")) {
            userName = "tea" + domain.getJobNum();
        } else if (domain.getRole().equals("student")) {
            userName = "stu" + domain.getJobNum();
        }
        User user1 = userRepository.findByUserNameAndDeleteFlag(userName, DataValidity.VALID.getState());
        if (!Objects.isNull(user1)) {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, "账号已存在!");
            return new ResponseEntity(result, HttpStatus.OK);
        }
        if (domain.getPassword() == null) {
            passwordEncode = PasswordUtil.encrypt(userName, "dingli123", salt);
        } else {
            passwordEncode = PasswordUtil.encrypt(userName, domain.getPassword().trim(), salt);
        }
        User userReg = new User();
        BeanUtils.copyProperties(domain, userReg);
        userReg.setPassWord(passwordEncode);
        userReg.setUserName(userName);
        userReg.setJobNum(domain.getJobNum());
        userReg.setClassId(domain.getClassId());
        userReg.setCollegeId(domain.getCollegeId());
        userReg.setProfessionalId(domain.getProfessionalId());
        userReg.setRole(domain.getRole());
        userReg.setSex(domain.getSex());
        User regUser = userService.save(userReg);
        result.put(ApiReturnConstants.SUCCESS, true);
        result.put(ApiReturnConstants.MESSAGE, regUser.getUserName());
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/addAdminAccount", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "POST", value = "新增管理员账号", response = Void.class, notes = "新增管理员账号")
    public ResponseEntity<?> addAdminAccount(@ApiParam(value = "新增管理员账号", required = false) @RequestBody AddAdminAccountDomain domain) {
        Map<String, Object> result = new HashMap();
        String salt = "ad9325e6";
        String passwordEncode = PasswordUtil.encrypt(domain.getUserName(), "dingli123", salt);
        User userReg = new User();
        BeanUtils.copyProperties(domain, userReg);
        if (!StringUtils.isEmpty(domain.getUserName())) {
            User user1 = userRepository.findByUserNameAndDeleteFlag(domain.getUserName(), DataValidity.VALID.getState());
            if (Objects.isNull(user1)) {
                userReg.setPassWord(passwordEncode);
                userReg.setUserName(domain.getUserName());
            } else {
                result.put(ApiReturnConstants.SUCCESS, false);
                result.put(ApiReturnConstants.ERROR, "账号已存在!");
                return new ResponseEntity(result, HttpStatus.OK);
            }
        }
        userReg.setRole(domain.getRole());
        User regUser = userService.save(userReg);
        result.put(ApiReturnConstants.SUCCESS, true);
        result.put(ApiReturnConstants.MESSAGE, regUser.getUserName());
        return new ResponseEntity(result, HttpStatus.OK);
    }


}

